import React, { useState, useCallback } from 'react';
import type { ChangeEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import styled from '@emotion/styled';
import Particles from 'react-tsparticles';
import { loadFull } from 'tsparticles';
import type { Engine } from 'tsparticles-engine';

const LoginContainer = styled.div`
  display: flex;
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #e0f7ff 0%, #b3e0ff 100%);
  position: relative;
  overflow: hidden;
`;

const ParticlesContainer = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
`;

const ContentContainer = styled.div`
  display: flex;
  width: 100%;
  height: 100vh;
  position: relative;
  z-index: 2;
`;

const WelcomeSection = styled.div`
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 2rem;
  color: #1a365d;
  animation: fadeIn 1s ease-in;

  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }
`;

const LoginSection = styled.div`
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2rem;
  animation: slideIn 1s ease-in;

  @keyframes slideIn {
    from { transform: translateX(50px); opacity: 0; }
    to { transform: translateX(0); opacity: 1; }
  }
`;

const LoginCard = styled.div`
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(10px);
  padding: 2rem;
  border-radius: 1rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
`;

const Input = styled.input`
  width: 100%;
  padding: 0.75rem;
  margin: 0.5rem 0;
  border: 2px solid #e2e8f0;
  border-radius: 0.5rem;
  font-size: 1rem;
  transition: all 0.3s ease;

  &:focus {
    outline: none;
    border-color: #0072ff;
    box-shadow: 0 0 0 3px rgba(0, 114, 255, 0.1);
  }
`;

const LoginButton = styled.button`
  width: 100%;
  padding: 0.75rem;
  margin-top: 1rem;
  background: linear-gradient(135deg, #0072ff 0%, #00c6ff 100%);
  color: white;
  border: none;
  border-radius: 0.5rem;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 12px rgba(0, 114, 255, 0.2);
  }
`;

const ErrorMessage = styled.div`
  color: #e53e3e;
  margin-top: 1rem;
  text-align: center;
`;

const WelcomeTitle = styled.h1`
  font-size: 2.5rem;
  margin-bottom: 1rem;
  text-align: center;
`;

const WelcomeSubtitle = styled.p`
  font-size: 1.2rem;
  color: #4a5568;
  text-align: center;
`;

const Login: React.FC = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const navigate = useNavigate();

  const particlesInit = useCallback(async (engine: Engine) => {
    await loadFull(engine);
  }, []);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
//      // 前端假登录
//   if (username === '1' && password === '1') {
//     navigate('/main');
//   } else {
//     setError('用户名或密码错误，请输入1/1进行假登录测试');
//   }
// };

    try {
      const response = await fetch('http://localhost:8111/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password }),
      });

      const data = await response.json();

      if (response.ok) {
        // 检查返回的数据结构是否符合预期
        if (data && data.data && data.data.userId && data.data.username) {
          localStorage.setItem('userId', data.data.userId);
          localStorage.setItem('username', data.data.username);
          navigate('/main');
        } else {
          // 如果数据结构不符合预期，也视为一种错误情况
          setError('登录成功，但响应数据格式不正确。');
        }
      } else {
        setError(data.message || '登录失败，请重试');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
    }
  };

  return (
    <LoginContainer>
      <ParticlesContainer>
        <Particles
          id="tsparticles"
          init={particlesInit}
          options={{
            background: {
              color: {
                value: "transparent",
              },
            },
            fpsLimit: 60,
            particles: {
              color: {
                value: ["#ffffff", "#b3e0ff"],
              },
              links: {
                color: "#ffffff",
                distance: 150,
                enable: true,
                opacity: 0.2,
                width: 1,
              },
              move: {
                enable: true,
                outModes: {
                  default: "bounce",
                },
                random: true,
                speed: 1,
                straight: false,
              },
              number: {
                density: {
                  enable: true,
                  area: 800,
                },
                value: 40,
              },
              opacity: {
                value: 0.5,
              },
              shape: {
                type: "circle",
              },
              size: {
                value: { min: 1, max: 3 },
              },
            },
            detectRetina: true,
            interactivity: {
              events: {
                onClick: {
                  enable: true,
                  mode: "push",
                },
                onHover: {
                  enable: true,
                  mode: "repulse",
                },
                resize: true,
              },
              modes: {
                push: {
                  quantity: 4,
                },
                repulse: {
                  distance: 100,
                  duration: 0.4,
                },
              },
            },
          }}
        />
      </ParticlesContainer>
      <ContentContainer>
        <WelcomeSection>
          <WelcomeTitle>欢迎来到 MindTalk</WelcomeTitle>
          <WelcomeSubtitle>很高兴见到你</WelcomeSubtitle>
        </WelcomeSection>
        
        <LoginSection>
          <LoginCard>
            <form onSubmit={handleLogin}>
              <Input
                type="text"
                placeholder="用户名"
                value={username}
                onChange={(e: ChangeEvent<HTMLInputElement>) => setUsername(e.target.value)}
              />
              <Input
                type="password"
                placeholder="密码"
                value={password}
                onChange={(e: ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}
              />
              <LoginButton type="submit">登录</LoginButton>
              {error && <ErrorMessage>{error}</ErrorMessage>}
            </form>
          </LoginCard>
        </LoginSection>
      </ContentContainer>
    </LoginContainer>
  );
};

export default Login;
